const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const chalk = require('chalk')

const deleteName = function () {
  let question = [
    {
      name: 'name',
      type: 'input',
      message: '请输入目录名称',
      validate(val) {
        if (val === '') {
          return '目录名称不能为空'
        } else if (/[\u4e00-\u9fa5]/g.test(val)) {
          return '目录名称不能包含中文'
        } else {
          return true
        }
      }
    }
  ]
  inquirer.prompt(question).then(answers => {
    dirDelete(answers.name)
  }).catch(err => {
    console.log(chalk.red(err))
  })
}

// 删除相关目录及文件
const dirDelete = function (name) {
  try {
    // module 目录
    delDir(path.resolve(process.cwd(), `./src/modules/${ name }`))
    // page 目录
    delDir(path.resolve(process.cwd(), `./src/pages/${ name }`))

    // html文件
    fs.unlink( path.resolve(process.cwd(), `./public/${ name }.html`))   
  } catch (err) {
    console.log(chalk.red(err))
  }  
}

function delDir(path){
    let files = [];
    if(fs.existsSync(path)){
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()){
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        fs.rmdirSync(path);
    }
}

deleteName()